<?php
/**
 * App 登录
 *
 * Author: Zeon
 * Date: 2017/11/20
 * Created by Panxsoft.
 */
namespace App\Http\Middleware;

use App\Exceptions\ApiException;
use App\Exceptions\ApiErrCode;
use App\Models\Customers\Customer;
use App\Services\Utils\ApiChecker;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\JWTGuard;

class AppAuth {

    use ApiChecker;

    /**
     *
     * @example composer require tymon/jwt-auth@1.0.0-beta.3
     * @link http://jwt-auth.readthedocs.io/en/docs/quick-start/
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     * @throws \Exception
     */
    public function handle(Request $request, Closure $next)
    {
        $this->checkToken($request);

        /** @var JWTGuard $jwt */
        $jwt = Auth::guard(Customer::GUARD_NAME);

        /** @var Customer $customer */
        $customer = $jwt->user();

        if (! $customer) {
            throw new ApiException(ApiErrCode::JWT_TOKEN_INVALID, trans('middleware.token_invalid'));
        }

        $this->checkCustomerStatus($customer);

        return $next($request);
    }

    /**
     * @param Request $request
     *
     * @throws \Exception
     */
    private function checkToken(Request $request)
    {
        if (config('app.debug_admin')) return;
        
        $this->checkJwtTokenExist($request,trans('checker.check_jwt_token_exist'));
    }

    /**
     *
     * @param Customer $customer
     * @throws \App\Exceptions\ApiAbstractException
     */
    private function checkCustomerStatus(Customer $customer): void
    {
        $this->checkIsTrue(
            $customer->status, trans('app.device_account_status')
        );
    }
}